package com.scalar.chiptrack.operations.tapereel.actioncommands;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.tapereel.TapeReelRequest;
import com.scalar.chiptrack.operations.tapereel.dao.TapeReelRequestDAO;
import com.scalar.chiptrack.operations.tapereel.forms.TapeReelRequestForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.Logger;
/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Apr 18, 2007
 * Time: 6:48:34 PM
 */
public class TapeReelRequestConfirmCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/tapeReelRequest.do";

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ScalarException
    {
        String actionType                       = request.getParameter("actionType");
        TapeReelRequestForm tapeReelRequestForm = (TapeReelRequestForm) form;
        TapeReelRequest tapeReelRequest         = tapeReelRequestForm.getTapeReelRequest();
        ActionForward actionForward             = mapping.findForward("search");
        HttpSession mSession                    = request.getSession();

        User user                               = (User) mSession.getAttribute(SessionKeys.USER_KEY);
        DBTransaction dbTransaction = null;
        HashMap<String, String> errors          = new HashMap<String,String>();
        HashMap<String,String> info             = new HashMap<String,String>();
        boolean error               = false;
        
        boolean isNewTapeReelRequest = ( tapeReelRequest.getTrRequestid() == -1 );
        
        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);

        if (user == null)
		{
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return (mapping.findForward("login"));
        }

        try
        {
            if(tapeReelRequest.getExpCompDate() != null && tapeReelRequest.getExpCompDate().trim().length() <= 0)
            {
               tapeReelRequest.setExpCompDate(null);
            }
            if(tapeReelRequest.getActualCompDate() != null && tapeReelRequest.getActualCompDate().trim().length() <= 0 )
            {
               tapeReelRequest.setActualCompDate(null);
            }

            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();

            TapeReelRequestDAO.saveTapeReelRequestDetails( dbTransaction, tapeReelRequest );
            TapeReelRequestDAO.saveTapeReelRequestLotDetails( dbTransaction, tapeReelRequest );

            info.put( "Tape & Reel Request Saved Successfully", null );
        }
        catch (Exception e)
        {
            e.printStackTrace();
            error = true;
            errors.put("Could not save the Tape & Reel Request", null);
        }

        finally
        {
            if (dbTransaction != null)
            {
                if (error == false)
                {
                    try
                    {
                        dbTransaction.commit();
                        //if (isNewTapeReelRequest) //SEND MAIL ONLY WHEN CREATING NEW SHIPPING REQUEST
                       // {
                            //TO LOAD THE SAVED Tape & Reel REQUEST INFO
                            TapeReelRequest savedTapeReelRequest = TapeReelRequestDAO.getTapeReelRequest(null, tapeReelRequest.getTrRequestid());
                            try
                            {
                                //TO SEND THE MAIL ALERTS TO VENDOR CONTACT PERSONS
                                if( "Issued".equalsIgnoreCase(savedTapeReelRequest.getReqStatus()) || "Closed".equalsIgnoreCase(savedTapeReelRequest.getReqStatus()))
                                {
                                    TapeReelRequestDAO.sendTapeReelRequestMail(savedTapeReelRequest, user );
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                                errors.put("Could not send Tape & Reel Request Request Email", null);
                            }

                       // }
                    }
                    catch (Exception e)
                    {
                        error = true;
                        e.printStackTrace();
                        Logger.debug("Error while committing the database update");
                    }
                }
                else
                {
                    try
                    {
                        dbTransaction.rollback();
                    }
                    catch (Exception e)
                    {
                        error = true;
                        Logger.debug("Error while rollback the database update");
                    }
                }
            }
        }
        /*if( error == false )
        {
            info.put( "Tape & Reel Request Saved Successfully",null );
            info.put ( "View/Print ,Click here to <a href='javascript:printView("+tapeReelRequest.getTrRequestid() +");' onmouseover=\"window.status='Click here to View/print Ship Request';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Tape & Reel Request Details", null );
        }*/

        TapeReelRequest tapeReelReq = new TapeReelRequest();
        tapeReelRequestForm.setTapeReelRequest(tapeReelReq);

        request.setAttribute("partNumbersList", TapeReelRequestDAO.loadTapeAndReelFgProducts() );
        request.setAttribute("vendorsList", TapeReelRequestDAO.getTrLocations());
        request.setAttribute("statusList", TapeReelRequest.getStatusList());
        tapeReelRequestForm.getTapeReelRequest().setReqStatus("Issued_Pulled");
        actionForward = mapping.findForward("search");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);

        request.setAttribute( "actionType", actionType );
        
        return actionForward;
    }
}
